<template>
  <!-- 计划维修表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="!props.isReadonly ? '1100px' : '1100px'"
    draggable
    @close="closeDialog"
    destroy-on-close
    align-center
    class="maxhDialog"
  >
    <div
      style="display: flex; justify-content: space-between; align-items: center"
      v-show="props.isReadonly"
    >
      <h4 class="mb-[20px] mt-[20px]">计划明细</h4>
    </div>
    <el-table
      v-show="props.isReadonly"
      ref="dataTableRef"
      v-loading="loading"
      :data="tableData"
      highlight-current-row
      border
    >
      <el-table-column type="index" width="55" align="center" />

      <el-table-column
        label="模具编号"
        prop="assetCode"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="模具名称"
        prop="assetName"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="模具类型"
        prop="assetTypeName"
        min-width="100"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column
        label="品牌型号"
        prop="assetBrandName"
        min-width="150"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          {{ scope.row.assetModelNo }}{{ scope.row.assetModelNo ? "-" : ""
          }}{{ scope.row.assetBrandName }}
        </template>
      </el-table-column>
      <el-table-column
        label="维修类型"
        prop="repairType"
        min-width="100"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          {{ useDictionary("PlanRepairType", scope.row.repairType) }}
        </template>
      </el-table-column>
      <el-table-column
        label="维修班组"
        prop="executeTeamName"
        min-width="100"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column
        label="维修人员"
        prop="executeUsers"
        min-width="150"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          {{ scope.row.executeUsers?.map((item) => item.personName).join(",") }}
        </template>
      </el-table-column>
      <el-table-column
        label="模具位置"
        prop="locationName"
        min-width="100"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column
        label="计划维修内容"
        prop="remarks"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="计划开始时间"
        prop="planStartTime"
        min-width="150"
        show-overflow-tooltip
        align="center"
      />
    </el-table>

    <div
      class="mb-[10px] mt-[20px] text-[15px]"
      v-show="props.isReadonly && formData.assetPhotos?.length"
    >
      附件上传
    </div>
    <el-row class="ml-[15px]">
      <CommonUploadFile
        v-show="props.isReadonly"
        :showText="formData.assetPhotos?.length > 0"
        :isRead="props.isReadonly"
        :files="formData.assetPhotos"
        @update-files="updateFormFiles"
      />
    </el-row>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
    <SelectMoldDialog-Eam
      v-model:visible="selectDialog.visible"
      :data="breakList"
      :equipTypeId="selectDialog.equipTypeId"
      @echo-info="changeVisible1"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";
import { useDictionary } from "../../../../../utils/useTable";
import { getStandardDevicesApi } from "@/utils/commonData";
import { ref } from "vue";
defineOptions({
  name: "COMMONREPAIRPLANADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: 3,
  },
});

const defaultUser = ref("");
const defaultDepart = ref("");
const defaultDepartName = ref("");

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
watch(
  () => props.assetKind,
  (newVal: number) => {},
  {
    immediate: true,
  }
);
const rules = reactive({
  version: [],
  // planCode: [
  //   { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  // ],
  planName: [
    { required: true, message: "请输入计划名称", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  repairType: [
    { required: true, message: "请选择维修类型", trigger: "change" },
  ],
  repariDirectorId: [
    { required: true, message: "请选择维修负责人", trigger: "change" },
  ],
  planStartTime: [
    { required: true, message: "请选择计划开始时间", trigger: "change" },
    { validator: validateStartTime, trigger: "change" },
  ],
  planEndTime: [
    { required: true, message: "请选择计划结束时间", trigger: "change" },
    { validator: validateEndTime, trigger: "change" },
  ],
  planRemindTime: [
    {
      message: "请输入1~100的数字",
      trigger: "blur",
      pattern: /^([1-9][0-9]?|100)$/,
    },
  ],
  planRemindTimeType: [
    { required: true, message: "请选择维修类型", trigger: "change" },
  ],
  equipTypeId: [
    { required: true, message: "请选择模具类型", trigger: "change" },
  ],
  deviceDepartment: [
    { required: true, message: "请选择模具管理部门", trigger: "change" },
  ],
  repairDepartment: [
    { required: true, message: "请选择维修执行部门", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});
// 校验
function validateEndTime(rule, value, callback) {
  if (formData.planStartTime && value < formData.planStartTime) {
    callback(new Error("结束日期不能小于开始日期"));
  } else {
    callback();
  }
}
// 校验
function validateStartTime(rule, value, callback) {
  if (formData.planEndTime && value > formData.planEndTime) {
    callback(new Error("开始日期不能大于结束日期"));
  } else {
    callback();
  }
}
const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  planCode: "",
  planName: "",
  repairType: "",
  equipTypeId: "",
  repariDirectorId: "",
  repariDirectorName: "",
  planStartTime: "",
  planEndTime: "",
  planRemindTime: "",
  planRemindTimeType: "0",
  deviceDepartment: "",
  deviceDepartmentName: "",
  repairDepartment: "",
  repairDepartmentName: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  planStatus: "",
  enabled: 1,
  deleted: "",
  details: [],
  assetPhotos: [],
  assetKind: props.assetKind,
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        planCode,
        planName,
        repairType,
        equipTypeId,
        repariDirectorId,
        repariDirectorName,
        planStartTime,
        planEndTime,
        planRemindTime,
        planRemindTimeType,
        deviceDepartment,
        deviceDepartmentName,
        repairDepartment,
        repairDepartmentName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        planStatus,
        deleted,
        assetKind,
        assetPhotos,
        details,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        planCode,
        planName,
        repairType,
        equipTypeId,
        repariDirectorId,
        repariDirectorName,
        planStartTime,
        planEndTime,
        planRemindTime,
        planRemindTimeType,
        deviceDepartment,
        deviceDepartmentName,
        repairDepartment,
        repairDepartmentName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        planStatus,
        deleted,
        assetKind,
        assetPhotos,
        details,
      });
      getTableList(id, assetKind);
      changePerson(repariDirectorId);
    } else {
      formData.assetKind = props.assetKind;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.planCode = "";
  formData.planName = "";
  formData.repairType = "";
  formData.equipTypeId = "";
  formData.repariDirectorId = defaultUser.value;
  formData.planStartTime = "";
  formData.planEndTime = "";
  formData.planRemindTime = "";
  formData.planRemindTimeType = "0";
  formData.deviceDepartment = defaultDepart.value;
  formData.deviceDepartmentName = defaultDepartName.value;
  formData.repairDepartment = defaultDepart.value;
  formData.repairDepartmentName = defaultDepartName.value;
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.details = [];
  formData.assetPhotos = [];
  formData.assetKind = props.assetKind;
  changePerson(defaultUser.value);
}

const loading = ref(false);

/** 计划维修保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/mouldrepairplan/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (item == "管理部门") {
    formData.deviceDepartment = ids;
  }
  if (item == "维修执行部门") {
    formData.repairDepartment = ids;
  }
}
/** 选择组织机构并赋值Name   start **/
function getSelectDatas(datas: any, item: any) {
  if (item == "管理部门") {
    formData.deviceDepartmentName = datas.organizationName
      ? datas.organizationName
      : "";
  }
  if (item == "维修执行部门") {
    formData.repairDepartmentName = datas.organizationName
      ? datas.organizationName
      : "";
  }
}
// 组织机构 placeholder值
const dataObject = (item: string) => {
  return {
    name: item == "管理部门" ? "管理部门" : "维修执行部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 人员改变时
const changePerson = (e: any) => {
  if (e) {
    personList.value.forEach((item: any) => {
      if (item.id == e) {
        formData.repariDirectorName = item.firstName;
      }
    });
  } else {
    formData.repariDirectorId = "";
    formData.repariDirectorName = "";
  }
};

const personList = ref([]);
const getPersonList = async () => {
  const res = await request({
    url: "/system/sysUser/getList",
    method: "post",
    data: {},
  });
  personList.value = res.data;
};
onMounted(async () => {
  await getPersonList();
  await getStandardList();
  await getDefaultUser();
  await getDefaultDepart();
});

const getDefaultUser = async () => {
  const res = await request({
    url: "/system/syssystemparam/getByCode/DEFAULT_USER/DEFAULT_USER",
    method: "get",
    data: {},
  });
  defaultUser.value = res.data.paramValue;
  formData.repariDirectorId = defaultUser.value;
  changePerson(defaultUser.value);
};

const getDefaultDepart = async () => {
  const res = await request({
    url: "/system/syssystemparam/getByCode/DEFAULT_DEPART/DEFAULT_DEPART",
    method: "get",
    data: {},
  });
  defaultDepart.value = res.data.paramValue;
  formData.deviceDepartment = defaultDepart.value;
  formData.repairDepartment = defaultDepart.value;
  const res2 = await request({
    url: "/system/syssystemparam/getByCode/DEFAULT_DEPART_NAME/DEFAULT_DEPART_NAME",
    method: "get",
    data: {},
  });
  defaultDepartName.value = res2.data.paramValue;
  formData.deviceDepartmentName = defaultDepartName.value;
  formData.repairDepartmentName = defaultDepartName.value;
};

const tableData = ref([]);

const getTableList = async (planId, assetKind) => {
  const { data } = await request({
    url: "/eam/eamrepairplandetail/getList",
    method: "post",
    data: { planId, assetKind },
  });
  tableData.value = data;
};

// 获取作业类型列表
const deviceList = ref(<any>[]);
async function getDeviceList() {
  const params = {
    assetKind: 3,
  };
  deviceList.value = (await getStandardDevicesApi(params)) ?? [];
}
getDeviceList();

const selectDialog = ref({
  visible: false,
  equipTypeId: "",
});
/** 添加行 */
const handleAdd = () => {
  selectDialog.value.visible = true;
  selectDialog.value.equipTypeId = formData.equipTypeId;
  if (formData.details.length > 0) {
    getBreakList();
  }
};

const changeVisible1 = (val: any) => {
  console.log("breakList.value", formData.details);
  const elderDetails = JSON.parse(JSON.stringify(formData.details ?? []));

  if (val && val.length) {
    formData.details = [];
    // console.log("返回的数据", val);
    val?.forEach((item: any) => {
      const current = elderDetails.filter(
        (self) => self.assetId === item.id
      )?.[0];
      if (current) {
        formData.details.push(current);
      } else {
        formData.details.push({
          assetId: item.id,
          assetCode: item.assetCode,
          assetName: item.assetName,
          locationBeforeGrantId: item.locationId,
          locationBeforeGrant: item.locationName,
          assetModelId: item.assetModelId,
          assetModelNo: item.assetModelNo,
          assetBrandId: item.assetBrandId,
          assetBrandName: item.assetBrandName,
          locationId: item.locationId,
          locationName: item.locationName,
          assetTypeId: item.assetTypeId,
          assetTypeCode: item.assetTypeCode,
          assetTypeName: item.assetTypeName,
          isSopStandard: false,
        });
      }
    });
  } else {
    formData.details = [];
  }
  // selectDialog.visible = val;
};

const breakList = ref(<any>[]);
const getBreakList = () => {
  breakList.value = [];
  formData.details.forEach((item: any) => {
    if (item.assetId) {
      breakList.value.push({
        id: item.assetId,
        assetCode: item.assetCode,
        assetName: item.assetName,
        locationId: item.locationBeforeGrantId,
        locationName: item.locationBeforeGrant,
      });
    }
  });
  console.log("回显的数据", breakList.value);
};
const handlePlanStartDate = async () => {
  const { data } = await request({
    url: "/eam/mouldrepairplan/getPlanNoByStartDate",
    method: "get",
    params: { planStartDate: formData.planStartTime, assetKind: 3 },
  });
  formData.planCode = data;
};
// 图片处理
function updateFormFiles(val: []) {
  formData.assetPhotos = val;
}

// 标准作业列表
const standardList = ref(<any>[]);
async function getStandardList() {
  const data = await request({
    url: "/eam/eamsopstandard/getList",
    method: "post",
    data: { sopTypeCode: formData.sopTypeCode || "" },
    // data: { sopTypeCode: "EquipPrecisionInspect" },
  }).finally(() => {});
  standardList.value = data.data;
}

function filterStandardName(id: string) {
  if (id) {
    const current =
      standardList.value?.filter((item: any) => item?.id === id)[0] ?? {};
    return current?.standardName || "";
  } else {
    return "";
  }
}

function filterEquipTypeName(id: string) {
  if (!id || !deviceList.value || deviceList.value.length === 0) {
    return "";
  }
  return flattenTreeIterative(deviceList.value, id);
}
function flattenTreeIterative(tree, id) {
  const stack = [...tree];

  while (stack.length > 0) {
    const node = stack.pop();
    if (node.id === id) {
      return node.assetTypeName;
    }

    // 将子节点加入栈中
    if (node.nodes && node.nodes.length > 0) {
      stack.push(...node.nodes);
    }
  }

  return "";
}

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};
</script>

<style scoped lang="scss">
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 160px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
